<template>
  <div class="edit-page">
    <BaseButton @click="goBack">
        <ChevronsLeft  class="icon-base"/>
      </BaseButton>
    <h2 class="page-title">修改头像</h2>
    <div class="avatar-upload">
      <div class="avatar-preview">
        <img :src="previewUrl || defaultAvatar" alt="当前头像" />
      </div>
      <label class="upload-button">
        选择图片
        <input 
          type="file" 
          accept="image/*" 
          @change="handleFileChange" 
          ref="fileInput"
        />
      </label>
    </div>
    <button class="save-button" @click="handleSave" :disabled="!hasChanges">保存修改</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import BaseButton from '@/components/BaseButton.vue'
import { ChevronsLeft } from 'lucide-vue-next'
import basicDetailIcon from '@/assets/icons/basic-detail.svg';
import defaultAvatarImg from '@/assets/1.svg'; // 需要添加默认头像图片

const router = useRouter();
const fileInput = ref(null);
const previewUrl = ref('');
const defaultAvatar = defaultAvatarImg;
const hasChanges = ref(false);
const icons = { basicDetail: basicDetailIcon };
const selectedFile = ref(null);

// 获取用户当前头像
onMounted(async () => {
  try {
    // 从本地存储或API获取当前用户头像
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
    if (userInfo.avatar) {
      previewUrl.value = userInfo.avatar;
    }
  } catch (error) {
    console.error('获取头像失败:', error);
  }
});

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!allowedTypes.includes(file.type)) {
      alert('只支持 JPG、PNG 和 GIF 格式的图片');
      return;
    }

    if (file.size > 5 * 1024 * 1024) { // 5MB限制
      alert('图片大小不能超过5MB');
      return;
    }
    
    const reader = new FileReader();
    reader.onload = (e) => {
      previewUrl.value = e.target.result;
      hasChanges.value = true;
      selectedFile.value = file;
    };
    reader.readAsDataURL(file);
  }
};

const handleSave = async () => {
  const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
  if (!userInfo.id) {
    alert('用户信息不完整，请重新登录')
    router.push('/login')
    return
  }

  if (!selectedFile.value) {
    alert('请先选择一个头像图片')
    return
  }

  // 假设您已将图片上传到某个存储服务，并获取了图片的URL
  // 这里以模拟上传过程为例
  try {
    // 模拟上传图片并获取URL
    const uploadedImageUrl = await uploadImage(selectedFile.value) // 您需要实现 uploadImage 方法

    // 更新用户的头像字段
    const response = await fetch(`http://localhost:4000/user/${userInfo.id}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        avatar: uploadedImageUrl
      })
    })

    if (!response.ok) {
      throw new Error('头像更新失败')
    }

    const updatedUser = await response.json()
    // 更新 localStorage 中的用户信息
    localStorage.setItem('user', JSON.stringify(updatedUser))
    alert('头像更新成功')
    router.push('/')
  } catch (error) {
    console.error('更新头像错误:', error)
    alert(error.message || '更新头像失败')
  }
}

// 实际的图片上传方法
const uploadImage = async (file) => {
  const formData = new FormData();
  formData.append('avatar', file);

  try {
    const response = await fetch('http://localhost:4000/upload', {
      method: 'POST',
      body: formData,
      headers: {
        // 不需要设置 Content-Type，因为使用 FormData 时浏览器会自动设置
        'Authorization': `Bearer ${localStorage.getItem('token')}` // 如果需要认证
      }
    });

    if (!response.ok) {
      throw new Error('上传图片失败');
    }

    const data = await response.json();
    if (!data.url) {
      throw new Error('服务器返回的数据格式错误');
    }

    return data.url;
  } catch (error) {
    console.error('上传图片失败:', error);
    throw new Error('上传图片失败，请重试');
  }
};

const goBack = () => router.go(-1);
</script>

<style scoped>
.edit-page {
  padding: var(--spacing-large);
}

icon-base {
  width: 24px;
  height: 24px;
  color: #1a1a1a;
}

.back-icon {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.page-title {
  text-align: center;
  margin-top: 90px;
  font-size: var(--font-size-xlarge);
}

.avatar-upload {
  margin-top: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 60px;
  overflow: hidden;
  border: 2px solid var(--primary-color);
  background-color: #f5f5f5;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

input[type="file"] {
  display: none;
}

.avatar-upload::after {
  content: '点击上传头像';
  padding: 10px 20px;
  background-color: var(--primary-color);
  color: white;
  border-radius: var(--border-radius-small);
  cursor: pointer;
  margin-top: 10px;
}

.save-button {
  width: 100%;
  padding: 15px;
  background-color: var(--primary-color);
  color: var(--text-light);
  border: none;
  border-radius: var(--border-radius-small);
  margin-top: 20px;
  cursor: pointer;
}

.upload-button {
  display: inline-block;
  padding: 10px 20px;
  background-color: var(--primary-color);
  color: white;
  border-radius: var(--border-radius-small);
  cursor: pointer;
  text-align: center;
  margin-top: 20px;
}

.upload-button input[type="file"] {
  display: none;
}

.save-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
